//
//  MainScreenViewController.m
//  iTimeline
//
//  Created by Mobioneer HV 01 on 1/8/13.
//  Copyright (c) 2013 Mobioneer Co., Ltd. All rights reserved.
//

#import "MainScreenViewController.h"
#import "Common.h"
#import "DetailTaskViewController.h"
#import "Define.h"
#import "TEditTaskk.h"
#import "SideSwipeTableViewCell.h"
#import "CustomCell.h"
#import "DiaryViewController.h"
#import "SettingViewController.h"
#import "AppDelegate.h"
#import "TimelineViewController.h"

#import "TNewTask.h"
#import "TaskData.h"
#import "CalendarView.h"
#define USE_GESTURE_RECOGNIZERS YES
#define BOUNCE_PIXELS 5.0
#define PUSH_STYLE_ANIMATION NO
#define BUTTON_LEFT_MARGIN -20.0
#define BUTTON_SPACING 80.0
@interface MainScreenViewController (PrivateStuff)

-(void) setupSideSwipeView;
-(UIImage*) imageFilledWith:(UIColor*)color using:(UIImage*)startImage;
- (void) addSwipeViewTo:(UITableViewCell*)cell direction:(UISwipeGestureRecognizerDirection)direction;
- (void) setupGestureRecognizers;
- (void) swipe:(UISwipeGestureRecognizer *)recognizer direction:(UISwipeGestureRecognizerDirection)direction;

@end

@implementation MainScreenViewController
@synthesize sideSwipeView, sideSwipeCell, sideSwipeDirection, animatingSideSwipe;
- (void)dealloc
{
    self.calView = nil;
    self.openCalendalButton = nil;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.calView = [[[NSBundle mainBundle] loadNibNamed:@"CalendarView" owner:self options:nil] objectAtIndex:0];
    self.calView.delegate = self;
    self.isHaveCalendar = NO;
    // Do any additional setup after loading the view from its nib.
    //[self showTabBar];
    //  UINavigationBar *naviBar = [ [UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    //[self.view addSubview:naviBar];
    NSDate *date = [NSDate date];
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
    [dateFormat setDateFormat:@"dd/MM/yyyy"];
    NSString *dateString = [dateFormat stringFromDate:date];
    self.navigationItem.title = dateString;
   // [self setData];
    UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithTitle:@"Add" style:UIBarButtonItemStylePlain
                                                                     target:self action:@selector(addTask:)];
    self.navigationItem.rightBarButtonItem = addButton;
    
    self.openCalendalButton = [[UIBarButtonItem alloc] initWithTitle:@"Calendar" style:UIBarButtonItemStylePlain
                                                                 target:self action:@selector(openCalendar:)];
    self.navigationItem.leftBarButtonItem = self.openCalendalButton;
    buttonData = [NSArray arrayWithObjects:
                 
                  
                  [NSDictionary dictionaryWithObjectsAndKeys:@"Edit", @"title", @"ca.png", @"image", nil],[NSDictionary dictionaryWithObjectsAndKeys:@"Delete", @"title", @"c.png", @"image", nil],
                 [NSDictionary dictionaryWithObjectsAndKeys:@"Back", @"title", @"back.png", @"image", nil], 
                  nil] ;
    buttons = [[NSMutableArray alloc] initWithCapacity:buttonData.count];
    
    self.sideSwipeView = [[UIView alloc] initWithFrame:CGRectMake(_tableView.frame.origin.x, _tableView.frame.origin.y, _tableView.frame.size.width, _tableView.rowHeight)];
    [self setupSideSwipeView];
    
    animatingSideSwipe = NO;
    [self setupGestureRecognizers];
    
    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeLeft:)];
   
  

    swipe.direction = UISwipeGestureRecognizerDirectionLeft;
   [self.tableView addGestureRecognizer:swipe];
    NSLog(@"%f",_tableView.frame.size.height);
    
    
    
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{

     [self removeSideSwipeView:YES];
}

- (void)viewDidAppear:(BOOL)animated{
    //CGRect frame1 = _tableView.frame;
  //  frame1.size.height = _tableView.contentSize.height;
  //  _tableView.frame = frame1;
}

-(void)setData
{
    NSError *error;
    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    //Get information
   
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"TaskData" inManagedObjectContext:delegate.managedObjectContext];
    [fetchRequest setEntity:entity];
    NSDate *today = [NSDate date];
   // NSPredicate *predicate =
     NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
                                       initWithKey:@"time"
                                        ascending:YES];
    
   [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
    NSArray *tempArr = [delegate.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    
   
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
    [dateFormat setDateFormat:@"dd/MM/yyyy"];
    NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"vi_VN"];
    [dateFormat setLocale:usLocale];
    
    //NSLog(@"fg:%i", [q count]);
    maData = nil;
    maData = [[NSMutableArray alloc] init];
   // NSLog(@"Tem ARR%i",[tempArr count]);
    NSLog(@"IN today: %@", [dateFormat stringFromDate:today]);

    for (TaskData *d in tempArr) {
        
        {
            NSLog(@"%i",[d.complete intValue]);
            if([[dateFormat stringFromDate:today] isEqualToString:[dateFormat stringFromDate:d.time]])
            {
                if([d.complete intValue] == 0)
                {
                   [maData addObject:d]; 
                }
            }
            
        }
    }
    
   
    
}

- (IBAction)openCalendar:(id)sender
{
    if (self.isHaveCalendar) {
        self.isHaveCalendar = NO;
        self.openCalendalButton.title = @"Calendar";
        [self.calView removeFromSuperview];
    }
    else
    {
        self.isHaveCalendar = YES;
        self.openCalendalButton.title = @"Back";
        [self.view addSubview:self.calView];
    }
}

-(IBAction)addTask:(id)sender
{
    TNewTask *newTask = [[TNewTask alloc] initWithNibName:@"TNewTask" bundle:nil];
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:self action:nil];
    self.navigationItem.backBarButtonItem = backButton;
    [self.navigationController pushViewController:newTask animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL) gestureRecognizersSupported
{
    if (!USE_GESTURE_RECOGNIZERS) return NO;
    
    // Apple's docs: Although this class was publicly available starting with iOS 3.2, it was in development a short period prior to that
    // check if it responds to the selector locationInView:. This method was not added to the class until iOS 3.2.
    return [[[UISwipeGestureRecognizer alloc] init] respondsToSelector:@selector(locationInView:)];
}

- (void) setupGestureRecognizers
{
    // Do nothing under 3.x
    if (![self gestureRecognizersSupported]) return;
    
    // Setup a right swipe gesture recognizer
    UISwipeGestureRecognizer* rightSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeRight:)] ;
    rightSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
    [_tableView addGestureRecognizer:rightSwipeGestureRecognizer];
    
    // Setup a left swipe gesture recognizer
  //  UISwipeGestureRecognizer* leftSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeLeft:)];
    //  leftSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionRight;
    [_tableView addGestureRecognizer:rightSwipeGestureRecognizer];
   // [_tableView addGestureRecognizer:leftSwipeGestureRecognizer];
    
}



# pragma - Setup slide menu

- (void) setupSideSwipeView
{
    // Add the background pattern
    self.sideSwipeView.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"dotted-pattern.png"]];
    
    // Overlay a shadow image that adds a subtle darker drop shadow around the edges
    UIImage* shadow = [[UIImage imageNamed:@"inner-shadow.png"] stretchableImageWithLeftCapWidth:0 topCapHeight:0];
    UIImageView* shadowImageView = [[UIImageView alloc] initWithFrame:sideSwipeView.frame] ;
    shadowImageView.alpha = 0.6;
    shadowImageView.image = shadow;
    shadowImageView.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    [self.sideSwipeView addSubview:shadowImageView];
    
    // Iterate through the button data and create a button for each entry
    CGFloat leftEdge = BUTTON_LEFT_MARGIN;
    for (NSDictionary* buttonInfo in buttonData)
    {
        // Create the button
        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
        
        // Make sure the button ends up in the right place when the cell is resized
        button.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin;
        
        // Get the button image
        UIImage* buttonImage = [UIImage imageNamed:[buttonInfo objectForKey:@"image"]];
       
        // Set the button's frame
        button.frame = CGRectMake(leftEdge + 50, sideSwipeView.center.y - buttonImage.size.height/2.0, buttonImage.size.width, buttonImage.size.height);
            //   NSLog(@"HAHA: %f",buttonImage.;
        // Add the image as the button's background image
        // [button setBackgroundImage:buttonImage forState:UIControlStateNormal];
        UIImage* grayImage = [self imageFilledWith:[UIColor colorWithWhite:0.9 alpha:1.0] using:buttonImage];
        [button setImage:grayImage forState:UIControlStateNormal];
        
        // Add a touch up inside action
        [button addTarget:self action:@selector(touchUpInsideAction:) forControlEvents:UIControlEventTouchUpInside];
        
        // Keep track of the buttons so we know the proper text to display in the touch up inside action
        [buttons addObject:button];
        
        // Add the button to the side swipe view
        [self.sideSwipeView addSubview:button];
        
        // Move the left edge in prepartion for the next button
        leftEdge = leftEdge + buttonImage.size.width + BUTTON_SPACING;
    }
}

# pragma - TableView

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [maData count];
}


    
  


- (void)tableView:(UITableView *)theTableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath1
{
    // If we are using gestures, then don't do anything
    if ([self gestureRecognizersSupported]) return;
    
    // Get the table view cell where the swipe occured
    UITableViewCell* cell = [theTableView cellForRowAtIndexPath:indexPath1];
    
    // Make sure we are starting out with the side swipe view and cell in the proper location
    [self removeSideSwipeView:NO];
    
    // If this isn't the cell that already has thew side swipe view and we aren't in the middle of animating
    // then start animating in the the side swipe view. We don't have access to the direction, so we always assume right
    if (cell!= sideSwipeCell && !animatingSideSwipe)
        [self addSwipeViewTo:cell direction:UISwipeGestureRecognizerDirectionRight];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}



- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // If we are using gestures, then don't allow editing
    if ([self gestureRecognizersSupported])
        return NO;
    else
        return YES;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath1
{
    static NSString *cellIdentifier = @"CustomCell";
    
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (cell == nil) {
        
        cell = [[NSBundle mainBundle] loadNibNamed:cellIdentifier owner:self options:nil][0];
        
    }
    TaskData *data = [maData objectAtIndex:indexPath1.row];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
   // [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
    [dateFormatter setDateFormat:@"hh:mm"];
  
    
    
        cell.workLB.text = [dateFormatter stringFromDate:data.time];
        cell.dateLB.text = data.taskName;
        int pri = [data.priority intValue];
        switch (pri) {
        case 1:
                cell.priority.backgroundColor = [[UIColor alloc]initWithPatternImage:[UIImage imageNamed:@"green-tick.png"]];
            break;
        case 2:
            cell.priority.backgroundColor = [[UIColor alloc]initWithPatternImage:[UIImage imageNamed:@"blue-tick.png"]];
            break;
        case 3:
            cell.priority.backgroundColor = [[UIColor alloc]initWithPatternImage:[UIImage imageNamed:@"red-tick.png"]];
            break;
        default:
            break;
        }
        
    
    return cell;
    //cell.textLabel.text = [NSString stringWithFormat:@"%d", indexPath.row];
    //  cell.supressDeleteButton = ![self gestureRecognizersSupported];
    
    
    
}



- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 55;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath1{
    DetailTaskViewController *detailTask = [[DetailTaskViewController alloc] initWithNibName:@"DetailTaskViewController" bundle:nil];
    
    NSLog(@"indexpath: %d", indexPath1.row);
    TaskData *data = [maData objectAtIndex:indexPath1.row];
    detailTask.data = data;
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:self action:nil];
    self.navigationItem.backBarButtonItem = backButton;
    [self.navigationController pushViewController:detailTask animated:YES];

    
}

// Called when a left swipe occurred
- (void)swipeLeft:(UISwipeGestureRecognizer *)recognizer
{
    [self swipe:recognizer direction:UISwipeGestureRecognizerDirectionRight];
    NSLog(@"Left");
}





// Handle a left or right swipe
- (void)swipe:(UISwipeGestureRecognizer *)recognizer direction:(UISwipeGestureRecognizerDirection)direction
{
    if (recognizer && recognizer.state == UIGestureRecognizerStateEnded)
    {
        // Get the table view cell where the swipe occured
        CGPoint location = [recognizer locationInView:_tableView];
        indexPath = [_tableView indexPathForRowAtPoint:location];
        UITableViewCell* cell = [_tableView cellForRowAtIndexPath:indexPath];
        
        // If we are already showing the swipe view, remove it
        //if (cell.frame.origin.x != 0)
        if(direction == UISwipeGestureRecognizerDirectionLeft)
        {
            [self removeSideSwipeView:YES];
            return;
        }
        
        // Make sure we are starting out with the side swipe view and cell in the proper location
        [self removeSideSwipeView:NO];
        
        // If this isn't the cell that already has thew side swipe view and we aren't in the middle of animating
        // then start animating in the the side swipe view
        if (cell!= sideSwipeCell && !animatingSideSwipe)
            [self addSwipeViewTo:cell direction:direction];
    }
}

#pragma mark Adding the side swipe view
- (void) addSwipeViewTo:(UITableViewCell*)cell direction:(UISwipeGestureRecognizerDirection)direction
{

    // Change the frame of the side swipe view to match the cell
    sideSwipeView.frame = cell.frame;
    
    // Add the side swipe view to the table below the cell
    [_tableView insertSubview:sideSwipeView belowSubview:cell];
    
    // Remember which cell the side swipe view is displayed on and the swipe direction
    self.sideSwipeCell = cell;
    sideSwipeDirection = direction;
    
    CGRect cellFrame = cell.frame;
    if (PUSH_STYLE_ANIMATION)
    {
        // Move the side swipe view offscreen either to the left or the right depending on the swipe direction
        sideSwipeView.frame = CGRectMake(direction == UISwipeGestureRecognizerDirectionLeft ? cellFrame.size.width : -cellFrame.size.width, cellFrame.origin.y, cellFrame.size.width, cellFrame.size.height);
    }
    else
    {
        // Move the side swipe view to offset 0
        sideSwipeView.frame = CGRectMake(0, cellFrame.origin.y, cellFrame.size.width, cellFrame.size.height);
    }
    
    // Animate in the side swipe view
    animatingSideSwipe = YES;
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.2];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(animationDidStopAddingSwipeView:finished:context:)];
    if (PUSH_STYLE_ANIMATION)
    {
        // Move the side swipe view to offset 0
        // While simultaneously moving the cell's frame offscreen
        // The net effect is that the side swipe view is pushing the cell offscreen
        sideSwipeView.frame = CGRectMake(0, cellFrame.origin.y, cellFrame.size.width, cellFrame.size.height);
    }
    cell.frame = CGRectMake(direction == UISwipeGestureRecognizerDirectionLeft ? cellFrame.size.width : -cellFrame.size.width, cellFrame.origin.y, cellFrame.size.width, cellFrame.size.height);
    [UIView commitAnimations];
}

// Note that the animation is done
- (void)animationDidStopAddingSwipeView:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
{
    animatingSideSwipe = NO;
}

#pragma mark Removing the side swipe view
// UITableViewDelegate
// When a row is selected, animate the removal of the side swipe view
- (NSIndexPath *)tableView:(UITableView *)theTableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath1
{
    [self removeSideSwipeView:YES];
    return indexPath1;
}

// UIScrollViewDelegate
// When the table is scrolled, animate the removal of the side swipe view
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self removeSideSwipeView:YES];
}

// When the table is scrolled to the top, remove the side swipe view
- (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView
{
    [self removeSideSwipeView:NO];
    return YES;
}

// Remove the side swipe view.
// If animated is YES, then the removal is animated using a bounce effect
- (void) removeSideSwipeView:(BOOL)animated
{
    // Make sure we have a cell where the side swipe view appears and that we aren't in the middle of animating
    if (!sideSwipeCell || animatingSideSwipe) return;
    
    if (animated)
    {
        // The first step in a bounce animation is to move the side swipe view a bit offscreen
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.3];
        if (sideSwipeDirection == UISwipeGestureRecognizerDirectionRight)
        {
            if (PUSH_STYLE_ANIMATION)
                sideSwipeView.frame = CGRectMake(-sideSwipeView.frame.size.width + BOUNCE_PIXELS,sideSwipeView.frame.origin.y,sideSwipeView.frame.size.width, sideSwipeView.frame.size.height);
            sideSwipeCell.frame = CGRectMake(BOUNCE_PIXELS, sideSwipeCell.frame.origin.y, sideSwipeCell.frame.size.width, sideSwipeCell.frame.size.height);
        }
        else
        {
            if (PUSH_STYLE_ANIMATION)
                sideSwipeView.frame = CGRectMake(sideSwipeView.frame.size.width - BOUNCE_PIXELS,sideSwipeView.frame.origin.y,sideSwipeView.frame.size.width, sideSwipeView.frame.size.height);
            sideSwipeCell.frame = CGRectMake(-BOUNCE_PIXELS, sideSwipeCell.frame.origin.y, sideSwipeCell.frame.size.width, sideSwipeCell.frame.size.height);
        }
        animatingSideSwipe = YES;
        [UIView setAnimationDelegate:self];
        [UIView setAnimationDidStopSelector:@selector(animationDidStopOne:finished:context:)];
        [UIView commitAnimations];
    }
    else
    {
        [sideSwipeView removeFromSuperview];
        sideSwipeCell.frame = CGRectMake(0,sideSwipeCell.frame.origin.y,sideSwipeCell.frame.size.width, sideSwipeCell.frame.size.height);
        self.sideSwipeCell = nil;
    }
}

#pragma mark Bounce animation when removing the side swipe view
// The next step in a bounce animation is to move the side swipe view a bit on screen
- (void)animationDidStopOne:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.2];
    if (sideSwipeDirection == UISwipeGestureRecognizerDirectionRight)
    {
        if (PUSH_STYLE_ANIMATION)
            sideSwipeView.frame = CGRectMake(-sideSwipeView.frame.size.width + BOUNCE_PIXELS*2,sideSwipeView.frame.origin.y,sideSwipeView.frame.size.width, sideSwipeView.frame.size.height);
        sideSwipeCell.frame = CGRectMake(BOUNCE_PIXELS*2, sideSwipeCell.frame.origin.y, sideSwipeCell.frame.size.width, sideSwipeCell.frame.size.height);
    }
    else
    {
        if (PUSH_STYLE_ANIMATION)
            sideSwipeView.frame = CGRectMake(sideSwipeView.frame.size.width - BOUNCE_PIXELS*2,sideSwipeView.frame.origin.y,sideSwipeView.frame.size.width, sideSwipeView.frame.size.height);
        sideSwipeCell.frame = CGRectMake(-BOUNCE_PIXELS*2, sideSwipeCell.frame.origin.y, sideSwipeCell.frame.size.width, sideSwipeCell.frame.size.height);
    }
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(animationDidStopTwo:finished:context:)];
    [UIView setAnimationCurve:UIViewAnimationCurveLinear];
    [UIView commitAnimations];
}

// The final step in a bounce animation is to move the side swipe completely offscreen
- (void)animationDidStopTwo:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
{
    [UIView commitAnimations];
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.2];
    if (sideSwipeDirection == UISwipeGestureRecognizerDirectionRight)
    {
        if (PUSH_STYLE_ANIMATION)
            sideSwipeView.frame = CGRectMake(-sideSwipeView.frame.size.width ,sideSwipeView.frame.origin.y,sideSwipeView.frame.size.width, sideSwipeView.frame.size.height);
        sideSwipeCell.frame = CGRectMake(0, sideSwipeCell.frame.origin.y, sideSwipeCell.frame.size.width, sideSwipeCell.frame.size.height);
    }
    else
    {
        if (PUSH_STYLE_ANIMATION)
            sideSwipeView.frame = CGRectMake(sideSwipeView.frame.size.width ,sideSwipeView.frame.origin.y,sideSwipeView.frame.size.width, sideSwipeView.frame.size.height);
        sideSwipeCell.frame = CGRectMake(0, sideSwipeCell.frame.origin.y, sideSwipeCell.frame.size.width, sideSwipeCell.frame.size.height);
    }
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(animationDidStopThree:finished:context:)];
    [UIView setAnimationCurve:UIViewAnimationCurveLinear];
    [UIView commitAnimations];
}

// When the bounce animation is completed, remove the side swipe view and reset some state
- (void)animationDidStopThree:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
{
    animatingSideSwipe = NO;
    self.sideSwipeCell = nil;
    [sideSwipeView removeFromSuperview];
}

#pragma mark Button touch up inside action
- (IBAction) touchUpInsideAction:(UIButton*)button
{
   
      
    
   NSUInteger index = [buttons indexOfObject:button];
   if(index == 0)
   {
              // Edit
       TEditTaskk *editTask = [[TEditTaskk alloc] initWithNibName:@"TEditTaskk" bundle:nil];
       TaskData *data = [maData objectAtIndex:indexPath.row];
       editTask.data = data;
       UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:self action:nil];
       self.navigationItem.backBarButtonItem = backButton;
       [self.navigationController pushViewController:editTask animated:YES];

   }
   else if(index == 1)
   {
       //Delete
       UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning!" message:@"Do you want to delete this task ?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
       alert.tag = 1;
       [alert show];
       

   }
   else if(index == 2)
   {
       UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning!" message:@"Do you want to complete this task ?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
       alert.tag = 2;
       [alert show];

   }
   
}
-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if(alertView.tag == 1)
    {
        NSLog(@"Al 1");
        if(buttonIndex == 1)
        {
            AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
            NSManagedObject *object = [maData objectAtIndex:indexPath.row];
            [delegate.managedObjectContext deleteObject:object];
            [delegate saveContext];
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Notify" message:@"Delete Successed!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [self removeSideSwipeView:YES];
            [self setData];
            [_tableView reloadData];
          //  CGRect frame1 = _tableView.frame;
         //   frame1.size.height = _tableView.contentSize.height;
          //  _tableView.frame = frame1;
            [alert show];
           
        }
    }
    else if(alertView.tag == 2)
    {
        NSLog(@"Al 2");
        if(buttonIndex == 1)
        {
               AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
               TaskData *object = [maData objectAtIndex:indexPath.row];
               object.complete = [[NSNumber alloc]initWithInt:1];
               [delegate saveContext];
               UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Notify" message:@"Complete Successed!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
               [self removeSideSwipeView:YES];
        
               [self setData];
               [_tableView reloadData];
              // CGRect frame1 = _tableView.frame;
              // frame1.size.height = _tableView.contentSize.height;
             //  _tableView.frame = frame1;
                [alert show];
        }
    }
}
#pragma mark Generate images with given fill color
// Convert the image's fill color to the passed in color
-(UIImage*) imageFilledWith:(UIColor*)color using:(UIImage*)startImage
{
    // Create the proper sized rect
    CGRect imageRect = CGRectMake(0, 0, CGImageGetWidth(startImage.CGImage), CGImageGetHeight(startImage.CGImage));
    
    // Create a new bitmap context
    CGContextRef context = CGBitmapContextCreate(NULL, imageRect.size.width, imageRect.size.height, 8, 0, CGImageGetColorSpace(startImage.CGImage), kCGImageAlphaPremultipliedLast);
    
    // Use the passed in image as a clipping mask
    CGContextClipToMask(context, imageRect, startImage.CGImage);
    // Set the fill color
    CGContextSetFillColorWithColor(context, color.CGColor);
    // Fill with color
    CGContextFillRect(context, imageRect);
    
    // Generate a new image
    CGImageRef newCGImage = CGBitmapContextCreateImage(context);
    UIImage* newImage = [UIImage imageWithCGImage:newCGImage scale:startImage.scale orientation:startImage.imageOrientation];
    
    // Cleanup
    CGContextRelease(context);
    CGImageRelease(newCGImage);
    
    return newImage;
}


-(void)viewWillAppear:(BOOL)animated
{
    
     [self removeSideSwipeView:YES];
    [self setData];
    [_tableView reloadData];
    
    
}
- (void)viewDidUnload
{
    self.tableView = nil;
    self.sideSwipeView = nil;
}

- (void) calendarView:(CalendarView*)calendarView didSelectDay:(NSDate*)date
{
    self.isHaveCalendar = NO;
    self.openCalendalButton.title = @"Calendar";
    NSLog(@"Selected %@",date);
    NSLog(@"Reload List");
    [calendarView removeFromSuperview];
}



@end
